package com.xiongwei.networkProgram;

import java.io.InputStream;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * Java提供了HttpClient作为新的HTTP客户端编程接口用于取代老的HttpURLConnection接口；
 * HttpClient使用链式调用并通过内置的BodyPublishers和BodyHandlers来更方便地处理数据.
 *
 * @author XiongWei
 * @date 2021/1/12
 */
public class HttpProgram {

    public static void main(String[] args) throws Exception {
        HttpProgram hp = new HttpProgram();
        hp.testHttpClient();
    }

    public void testHttpURLConnection() {
        try {
            URL url = new URL("https://www.baidu.com");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setUseCaches(false);
            // 请求超时5秒
            conn.setConnectTimeout(5000);
            // 设置HTTP头:
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 11; Windows NT 5.1)");
            // 连接并发送HTTP请求:
            conn.connect();
            // 判断HTTP响应是否200:
            if (conn.getResponseCode() != 200) {
                System.out.println(conn.getResponseCode());
                throw new RuntimeException("bad response");
            }
            // 获取所有响应Header:
            Map<String, List<String>> map = conn.getHeaderFields();
            for (String key : map.keySet()) {
                System.out.println(key + ": " + map.get(key));
            }
            // 获取响应内容:
            //InputStream input = conn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testHttpClient() throws Exception {
        final HttpClient httpClient = HttpClient.newBuilder().build();
        String url = "https://www.baidu.com/";
        HttpRequest request = HttpRequest.newBuilder(new URI(url))
                // 设置Header:
                .header("User-Agent", "Java HttpClient").header("Accept", "*/*")
                // 设置超时:
                .timeout(Duration.ofSeconds(5))
                // 设置版本:
                .version(HttpClient.Version.HTTP_2).build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        // HTTP允许重复的Header，因此一个Header可对应多个Value:
        Map<String, List<String>> headers = response.headers().map();
        for (String header : headers.keySet()) {
            System.out.println(header + ": " + headers.get(header).get(0));
        }
        System.out.println(response.body().substring(0, 1024) + "...");
    }
}
